package com.dongbo.recorder.screenrecord;

import android.app.Activity;
import android.view.View;
import android.widget.Toast;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.dongbo.recorder.screenrecord.utils.ScreenUtils;

import java.util.List;

public class LoadAd {
    //    private static class LoadAdHolder {
//        private static final LoadAd INSTANCE = new LoadAd();
//    }
    public LoadAd() {
        //单例设为私有
    }

//    public static final LoadAd getInstance() {
//        return LoadAdHolder.INSTANCE;
//    }

    private TTAdNative mTTAdNative;
    private TTNativeExpressAd mTTAd;
    private Activity mContext;
    //    private FrameLayout mExpressContainer;
    private boolean mHasShowDownloadActive = false;

    //    public void initTTSDKConfig(Activity mContext, FrameLayout mExpressContainer) {
    public void initTTSDKConfig(Activity mContext, String codeId, OnAdEventListener onAdEventListener) {
        if (!AppLpds.getInstance().isShowAd()) {
            return;
        }
        this.mContext = mContext;
        this.onAdEventListener = onAdEventListener;
//        this.mExpressContainer = mExpressContainer;
        //step2:创建TTAdNative对象，createAdNative(Context context) banner广告context需要传入Activity对象
        mTTAdNative = TTAdSdk.getAdManager().createAdNative(mContext);
        //step3:(可选，强烈建议在合适的时机调用):申请部分权限，如read_phone_state,防止获取不了imei时候，下载类广告没有填充的问题。
        TTAdSdk.getAdManager().requestPermissionIfNecessary(mContext);
        loadExpressAd(codeId);
    }

    private void loadExpressAd(String codeId) {
        onAdEventListener.removeAllViews();
        //step4:创建广告请求参数AdSlot,具体参数含义参考文档
        AdSlot adSlot = null;
        if (codeId.equals(Constants.ADV_ID)) {
            adSlot = new AdSlot.Builder()
                    .setCodeId(codeId) //广告位id
                    .setAdCount(1) //请求广告数量为1到3条
                    .setExpressViewAcceptedSize(ScreenUtils.getScreenWidth(), 150) //期望模板广告view的size,单位dp
                    .build();
        } else {
            adSlot = new AdSlot.Builder()
                    .setCodeId(codeId) //广告位id
                    .setAdCount(1) //请求广告数量为1到3条
                    .setExpressViewAcceptedSize(ScreenUtils.getScreenWidth(), 150) //期望模板广告view的size,单位dp
                    .build();
        }
        //step5:请求广告，对请求回调的广告作渲染处理

        mTTAdNative.loadBannerExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {
                onAdEventListener.onLoadError(code, message);
            }

            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (ads == null || ads.size() == 0) {
                    return;
                }
                mTTAd = ads.get(0);
                mTTAd.setSlideIntervalTime(15 * 1000);
                bindAdListener(mTTAd);
                onClickShowBanner();
            }
        });
    }

    public void onClickShowBanner() {
        if (mTTAd != null) {
            mTTAd.render();//提交
        } else {
            Toast.makeText(mContext, "广告加载失败～", Toast.LENGTH_LONG).show();
        }
    }

    private void bindAdListener(TTNativeExpressAd ad) {
        ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
            @Override

            public void onAdClicked(View view, int type) {
//                TToast.show(mContext, "广告被点击");
            }

            @Override

            public void onAdShow(View view, int type) {
//                TToast.show(mContext, "广告展示");
            }

            @Override
            public void onRenderFail(View view, String msg, int code) {
            }

            @Override
            public void onRenderSuccess(View view, float width, float height) {
                //返回view的宽高 单位 dp
                onAdEventListener.addAllViews(view, width, height);
//                mExpressContainer.removeAllViews();
//                mExpressContainer.addView(view);
            }
        });
        //dislike设置
        bindDislike(ad, false);

        if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
            return;
        }
        ad.setDownloadListener(new TTAppDownloadListener() {
            @Override
            public void onIdle() {
//                Toast.makeText(mContext,"点击开始下载～",Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
                if (!mHasShowDownloadActive) {
                    mHasShowDownloadActive = true;
                    Toast.makeText(mContext, "下载中，点击暂停", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
                if (mHasShowDownloadActive)
                    Toast.makeText(mContext, "下载暂停，点击继续", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
                if (mHasShowDownloadActive)
                    Toast.makeText(mContext, "下载失败，点击重新下载", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onInstalled(String fileName, String appName) {
                if (mHasShowDownloadActive)
                    Toast.makeText(mContext, "安装完成，点击图片打开", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onDownloadFinished(long totalBytes, String fileName, String appName) {
                if (mHasShowDownloadActive) {
                    Toast.makeText(mContext, "点击安装", Toast.LENGTH_LONG).show();
                    mHasShowDownloadActive = false;
                }
            }
        });
    }

    /**
     * 设置广告的不喜欢, 注意：强烈建议设置该逻辑，如果不设置dislike处理逻辑，则模板广告中的 dislike区域不响应dislike事件。
     *
     * @param ad
     * @param customStyle 是否自定义样式，true:样式自定义
     */
    private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
        //使用默认模板中默认dislike弹出样式
        ad.setDislikeCallback(mContext, new TTAdDislike.DislikeInteractionCallback() {
            @Override
            public void onShow() {

            }

            @Override
            public void onSelected(int position, String value, boolean enforce) {
//                mExpressContainer.removeAllViews();
                onAdEventListener.closeAd(position, value, enforce);
            }

            @Override
            public void onCancel() {
            }

        });
    }

    public void onDestroyView() {
        if (mTTAd != null) {
            mTTAd.destroy();
        }
    }

    private OnAdEventListener onAdEventListener;

    public interface OnAdEventListener {
        void removeAllViews();

        void onLoadError(int code, String message);

        void addAllViews(View view, float width, float height);

        void closeAd(int position, String value, boolean enforce);
    }

}
